#include <jni.h>
#include <string>
#include <curl.h>
#include <easy.h>
#include <android/log.h>
#include "value.h"
#include "writer.h"
#include "sqlite3.h"

#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"carson",__VA_ARGS__)

// 回调函数，用于写入 CURL 返回的数据
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_android_carson_curl_NativeBridge_httpWithCurl(JNIEnv* env, jobject thiz, jstring url) {

    const char* nativeUrl = env->GetStringUTFChars(url, nullptr);
    std::string readBuffer;

    CURL* curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, nativeUrl);
        curl_easy_setopt(curl, CURLOPT_URL, nativeUrl);  // 使用传入的 URL
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // 设置写回调
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);       // 设置写入缓冲区

        // 可选设置，跳过 HTTPS 证书校验（仅测试用不校验https用0，生产使用1）
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            LOGI("curl_easy_perform() failed: %s", curl_easy_strerror(res));
            readBuffer = "Curl error: " + std::string(curl_easy_strerror(res));
        } else {
            LOGI("HTTP response: %s", readBuffer.c_str());
        }
        curl_easy_cleanup(curl);
    } else {
        readBuffer = "Curl init failed.";
    }
    env->ReleaseStringUTFChars(url, nativeUrl); // 释放 Java 字符串资源
    return env->NewStringUTF(readBuffer.c_str());
}


extern "C" JNIEXPORT jstring JNICALL
Java_com_android_carson_curl_NativeBridge_testWithJsonCpp(JNIEnv* env, jobject thiz) {
    // TODO: implement testWithJsonCpp()
    Json::Value root;
    root["code"] = 200;
    root["msg"] = "success";

    Json::Value data;
    data["name"] = "carson";
    data["id"] = 123;

    root["data"] = data;

    Json::StreamWriterBuilder writerBuilder;
    writerBuilder["indentation"] = ""; // 紧凑格式

    std::string jsonStr = Json::writeString(writerBuilder, root);

    LOGI("Native JSON: %s", jsonStr.c_str());

    return env->NewStringUTF(jsonStr.c_str());
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_android_carson_curl_NativeBridge_testSqlite3(JNIEnv* env, jobject thiz) {
    sqlite3* db;
    char* errMsg = nullptr;

    // 在内存中创建数据库
    int rc = sqlite3_open(":memory:", &db);
    if (rc != SQLITE_OK) {
        LOGI("无法打开数据库: %s", sqlite3_errmsg(db));
        return env->NewStringUTF("DB open failed");
    }

    // 创建表
    const char* create_sql = "CREATE TABLE user (id INTEGER, name TEXT);";
    rc = sqlite3_exec(db, create_sql, nullptr, nullptr, &errMsg);
    if (rc != SQLITE_OK) {
        LOGI("创建表失败: %s", errMsg);
        sqlite3_free(errMsg);
        sqlite3_close(db);
        return env->NewStringUTF("Create table failed");
    }

    // 插入一条数据
    const char* insert_sql = "INSERT INTO user VALUES (1, 'Alice');";
    rc = sqlite3_exec(db, insert_sql, nullptr, nullptr, &errMsg);
    if (rc != SQLITE_OK) {
        LOGI("插入数据失败: %s", errMsg);
        sqlite3_free(errMsg);
        sqlite3_close(db);
        return env->NewStringUTF("Insert failed");
    }

    // 查询数据
    const char* query_sql = "SELECT id, name FROM user;";
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db, query_sql, -1, &stmt, nullptr);
    if (rc != SQLITE_OK) {
        LOGI("查询准备失败: %s", sqlite3_errmsg(db));
        sqlite3_close(db);
        return env->NewStringUTF("Query prepare failed");
    }

    // 使用 jsoncpp 构建 JSON 返回
    Json::Value result(Json::arrayValue);

    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int id = sqlite3_column_int(stmt, 0);
        const unsigned char* nameText = sqlite3_column_text(stmt, 1);

        Json::Value user;
        user["id"] = id;
        user["name"] = nameText ? (const char*)nameText : "";

        result.append(user);
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);

    Json::StreamWriterBuilder writerBuilder;
    writerBuilder["indentation"] = "";  // 紧凑格式
    std::string jsonStr = Json::writeString(writerBuilder, result);

    LOGI("SQLite JSON: %s", jsonStr.c_str());

    return env->NewStringUTF(jsonStr.c_str());
}